package pattern.observer.events.core;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author juxiaojun
 * @since 2019-05-11
 */
public class EventListener {
    //JDK底层的设计也是这样的
    private Map<String,Event> events=new HashMap<String, Event>();

    //事件名称和一个目标对象来触发事件
    public void addListener(String eventType,Object target){
        try {
            this.addListener(eventType,target,target.getClass().getMethod("on"+toUpperFirstCase(eventType),Event.class));
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public void addListener(String eventType, Object target, Method callback){
        this.events.put(eventType,new Event(target, callback));
    }
    //只要有动作就会触发
    private void trigger(Event event){
        event.setSource(this);
        event.setTime(System.currentTimeMillis());
        try{
            if(null!=event.getCallback()){
                event.getCallback().invoke(event.getTarget(),event);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //事件名称触发
    protected void trigger(String trigger){
        if(!this.events.containsKey(trigger)) return;
        this.trigger(this.events.get(trigger).setTrigger(trigger));
    }

    //逻辑处理的私有方法，首字母大写
    private String toUpperFirstCase(String str){
        char[] chars = str.toCharArray();
        chars[0] -= 32;
        return String.valueOf(chars);
    }
}
